# DjangoDE, an integrated development environment for Django
# Copyright (C) 2010-2011 Andrew Wilkinson
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.

import sys
import tempfile
import unittest

from djangode import global_objects
from djangode.gui import MainWindow
from djangode.gui.python_editor import PythonEditor
from djangode.utils.qt import Qt, QtCore, QtGui

class TestPythonEditorSave(unittest.TestCase):
    def setUp(self):
        if hasattr(sys, "last_type"):
            del sys.last_type

        global_objects.main_window = MainWindow()

    def tearDown(self):
        global_objects.main_window.close()
        global_objects.main_window = None

    def test_save_file(self):
        temp_file = tempfile.NamedTemporaryFile(suffix=".py")

        global_objects.main_window.editor.open_file[(str, )].emit(temp_file.name)
        global_objects.app.processEvents()

        editor = global_objects.main_window.editor.widget(0)
        self.send_keypresses(editor, """
# This is some test code.
""")

        global_objects.main_window.actions["save_file"].trigger()
        self.assert_(not hasattr(sys, "last_type")) # Check that there were no exceptions while processing events.

        temp_file.seek(0)
        self.assert_("This is some test code." in temp_file.read())

    def send_event(self, editor, event):
        global_objects.app.sendEvent(editor.completer.popup() if editor.completer.popup().isVisible() else editor, event)
        global_objects.app.processEvents()

    def send_keypresses(self, editor, text):
        for key in text:
            self.send_event(editor, QtGui.QKeyEvent(QtCore.QEvent.KeyPress, ord(key), QtCore.Qt.NoModifier, key))
